//
//  GTListLoader.m
//  SampleApp2
//
//  Created by GXHC on 2023/6/14.
//

#import <AFNetworking.h>
#import "GTListItem.h"
#import "GTListLoader.h"
#import <YYModel/YYModel.h>

@implementation GTListLoader

- (void)loadListData {
	
	
	
    NSString *urlString = @"https://static001.geekbang.org/univer/classes/ios_dev/lession/45/toutiao.json";
    NSURL *listURL = [NSURL URLWithString:urlString];

    __unused NSURLRequest *request = [NSURLRequest requestWithURL:listURL];
    NSURLSession *session = [NSURLSession sharedSession];
//	NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError *_Nullable error) {
        NSError *jsonError;
        id jsonObj =  [NSJSONSerialization JSONObjectWithData:data
                                                      options:NSJSONReadingMutableLeaves
                                                        error:&jsonError];
        NSArray *dataArray = [((NSDictionary *)[((NSDictionary *)jsonObj)objectForKey:@"result"]) objectForKey:@"data"];
        NSMutableArray *listItemArray = @[].mutableCopy;

        for (NSDictionary *info in dataArray) {
            GTListItem *item = [[GTListItem alloc]initWithDictionary:info];
			item.url = @"http://up.deskcity.org/pic_source/2f/f4/42/2ff442798331f6cc6005098766304e39.jpg";
            [listItemArray addObject:item];
        }

        NSLog(@"%@", jsonObj);
    }];

    [dataTask resume];

//	[[AFHTTPSessionManager manager]GET:urlString parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//			NSLog(@"");
//
//		} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//			NSLog(@"");
//		} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//			NSLog(@"");
//		}];
}

- (void)loadListDataWithFinishBlck:(GTListLoaderFinishBlock)finishBlock {
	NSArray<GTListItem *> *listData = [self _readDataFromLocal];
	if(listData){
		finishBlock(YES, listData);
		return;
	}
    NSString *urlString = @"https://static001.geekbang.org/univer/classes/ios_dev/lession/45/toutiao.json";
    NSURL *listURL = [NSURL URLWithString:urlString];

    __unused NSURLRequest *request = [NSURLRequest requestWithURL:listURL];
    NSURLSession *session = [NSURLSession sharedSession];
//	NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
	__weak typeof(self) wself = self;
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError *_Nullable error) {
		__strong typeof(wself) strongSelf = wself;
        NSError *jsonError;
        id jsonObj =  [NSJSONSerialization JSONObjectWithData:data
                                                      options:NSJSONReadingMutableLeaves
                                                        error:&jsonError];
        NSArray *dataArray = [((NSDictionary *)[((NSDictionary *)jsonObj)objectForKey:@"result"]) objectForKey:@"data"];
        NSMutableArray *listItemArray = @[].mutableCopy;

        for (NSDictionary *info in dataArray) {
			GTListItem *item = [GTListItem yy_modelWithJSON:info];
            //GTListItem *item = [[GTListItem alloc]initWithDictionary:info];
			item.thumbnailPicS = @"https://img1.baidu.com/it/u=4009907374,3946217754&fm=253&fmt=auto?w=130&h=170";
            [listItemArray addObject:item];
        }
		[strongSelf _archiveListDataWithArray:listItemArray.copy];
        dispatch_async(dispatch_get_main_queue(), ^{
                           if (finishBlock) {
                               finishBlock(error == nil, listItemArray.copy);
                           }
		});

//		NSLog(@"%@",jsonObj);
    }];

    [dataTask resume];
//	[self _getSandBoxPath];
	
}

- (NSArray<GTListItem *> *)_readDataFromLocal{
	NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
	NSString *cachePath = [pathArray firstObject];
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString *listDataPath = [cachePath stringByAppendingPathComponent:@"GTData/list"];
	NSData *readListData = [fileManager contentsAtPath:listDataPath];
	id unarchiveObj = [NSKeyedUnarchiver unarchivedObjectOfClasses:
					   [NSSet setWithObjects:[NSArray class], [GTListItem class],[NSString class], nil] fromData:readListData error: nil];
	if([unarchiveObj isKindOfClass:[NSArray class]] && [unarchiveObj count] > 0){
		return unarchiveObj;
	}
	return nil;
}

-(void)_archiveListDataWithArray:(NSArray<GTListItem *> *)dataArray{
	NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
	NSString *cachePath = [pathArray firstObject];
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString *dataPath = [cachePath stringByAppendingPathComponent:@"GTData"];
	NSError *createError;
	[fileManager createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&createError];
	NSString *listDataPath = [dataPath stringByAppendingPathComponent:@"list"];
	
	NSData *listData = [NSKeyedArchiver archivedDataWithRootObject:dataArray requiringSecureCoding:YES error:nil];
	
	
	[fileManager createFileAtPath:listDataPath contents:listData attributes:nil];
	
	NSData *readListData = [fileManager contentsAtPath:listDataPath];
	
	id unarchiveObj = [NSKeyedUnarchiver unarchivedObjectOfClasses:
					   [NSSet setWithObjects:[NSArray class], [GTListItem class],[NSString class], nil] fromData:readListData error: nil];
	
//	[[NSUserDefaults standardUserDefaults] setObject:@"abc" forKey:@"test"];
//	NSString *test = [[NSUserDefaults standardUserDefaults] stringForKey:@"test"];
//	NSLog(@"%@",test);
	
//	[[NSUserDefaults standardUserDefaults] setObject:listData forKey:@"listData"];
//	NSData *test = [[NSUserDefaults standardUserDefaults] dataForKey:@"listData"];
//	NSLog(@"%@",test);
}



-(void)_getSandBoxPath{
//	NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//	NSLog(@"");
	
	NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
	NSString *cachePath = [pathArray firstObject];
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString *dataPath = [cachePath stringByAppendingPathComponent:@"GTData"];
	NSError *createError;
	[fileManager createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&createError];
	NSString *listDataPath = [dataPath stringByAppendingPathComponent:@"list"];
	NSData *listData = [@"abc" dataUsingEncoding:NSUTF8StringEncoding];
	[fileManager createFileAtPath:listDataPath contents:listData attributes:nil];
//	BOOL fileExist = [fileManager fileExistsAtPath:listDataPath];
//	if(fileExist){
//		[fileManager removeItemAtPath:listDataPath error:nil];
//	}
	
	NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:listDataPath];
	[fileHandle seekToEndOfFile];
	NSData *data = [@"def" dataUsingEncoding:NSUTF8StringEncoding];
	[fileHandle writeData:data];
	
	[fileHandle synchronizeFile];
	[fileHandle closeFile];
	
	NSLog(@"");
	
	
	
}

@end
